package com.hotel.controller;

import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.util.IdUtil;
import com.hotel.bean.Admin;
import com.hotel.bean.RespBean;
import com.hotel.exception.SteduException;
import com.hotel.service.AdminService;
import com.hotel.utils.JwtUtil;
import com.hotel.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@CrossOrigin
public class AdminController {
    @Autowired
    private AdminService adminService;
    //登录验证
    @Autowired
    private RedisUtil redisUtil;
    @PostMapping("/login")
    public RespBean login(String username, String password,String captchaId,String captcha) throws SteduException {
        String captchaRedis = (String) redisUtil.get(captchaId);
        if(captchaRedis == null){
            return RespBean.error("验证码过期");
        }
        if(captchaRedis != null && !captchaRedis.equalsIgnoreCase(captcha)){
            return RespBean.error("验证码输出错误,请重新输入");
        }
        Admin admin = adminService.selectUsernamePassword(username, password);
        Map<String,Object> map = new HashMap<>();
        map.put("aid",admin.getAid());
        map.put("username",admin.getUsername());
        String jwt = JwtUtil.generateJwt(map);
        return RespBean.ok("登陆成功",jwt);
    }
    //退出登录

    @GetMapping("/logout")
    public RespBean logout(HttpSession session)  {
        session.invalidate();
        return RespBean.ok("退出成功");
    }
    //验证码

    @GetMapping("/captcha")
    public RespBean captcha() throws IOException {
        LineCaptcha lineCaptcha = new LineCaptcha(120, 38, 4, 20);
        //获取验证码文本
        String code = lineCaptcha.getCode();
        //生成唯一ID - 雪花算法
        String captchaId = IdUtil.getSnowflakeNextIdStr();
        redisUtil.set(captchaId,code,60);
        String captchaImageBase64Data = lineCaptcha.getImageBase64Data();
        Map<String,Object> map = new HashMap<>();
        map.put("captchaId",captchaId);
        map.put("captchaImageBase64Data",captchaImageBase64Data);
        return RespBean.ok("",map);
    }
}
